package com.hrhx.springboot.web;

import java.io.File;
import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.lionsoul.ip2region.service.DataBlock;
import org.lionsoul.ip2region.service.DbConfig;
import org.lionsoul.ip2region.service.DbSearcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = "/ipregion")
public class Ip2RegionRestController {
	
	private Logger log = Logger.getLogger(Ip2RegionRestController.class);
	
	@Value("${ip.region.db.file}")
	private String dbFile;
	
	@ApiOperation(value = "根据IP地址获取地理信息", notes = "")
	@RequestMapping(value = "/query", method = RequestMethod.GET)
	public DataBlock getByParentId(
			@ApiParam(required = true, name = "ip", value= "测试IP地址：202.96.64.68") @RequestParam( value = "ip") String ip
			) throws Exception {
		
		DataBlock dataBlock = null;
		File file = new File(dbFile);
		
		if(file.isFile()){
			
			DbConfig config = new DbConfig();
	        DbSearcher searcher = new DbSearcher(config,dbFile);
	        log.info("dbFile载入成功，路径为："+dbFile);
	        Method method = searcher.getClass().getMethod("btreeSearch", String.class);
	        dataBlock = (DataBlock) method.invoke(searcher, ip);
	        searcher.close();
	        
		}else{
			
			log.error("dbFile载入失败，路径为："+dbFile);
			log.error("请在application.properties中ip.region.db.file配置并仔细核对");
		}
        return dataBlock;
	}
}
